package com.cgmnx.admin.common.bean;

import com.cgmnx.admin.common.exception.BizException;
import com.cgmnx.admin.common.exception.CgmnxException;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Slf4j
public abstract class Template<T> {

    protected Logger logger = LoggerFactory.getLogger(getClass());

    private String name;

    protected Template() {
    }

    public Template(String name) {
        this.name = name;
    }

    protected void check() {
    }

    protected abstract T exec() throws Exception;

    protected void afterProcess() {
    }

    protected void onSuccess() {
    }

    protected void onError(Throwable e) {
    }

    public T execute() throws BizException {
        try {
            check();
        } catch (CgmnxException e) {
            throw e;
        } catch (Exception e) {
            throw new BizException(e.getMessage());
        }

        long startTime = System.currentTimeMillis();
        try {
            T result = exec();
            onSuccess();
            return result;
        } catch (CgmnxException biz) {
            onError(biz);
            throw biz;
        } catch (Throwable e) {
            onError(e);
            throw new BizException("操作出错了哦", e);
        } finally {
            afterProcess();
        }
    }
}
